import React, { useState, useEffect } from 'react'
import { Button, Spinner } from 'reactstrap'
import BoardItem from './Item/BoardItem';

const Board = (props) => {
    const [msg, setMsg] = useState('');
    const [issend, setIsSend] = useState(false);
    const [msglist, setMsglist] = useState([])

    useEffect(() => {
        let getdata = async () => {
            let resp =await fetch('/api/index/getLamByUserid?userid=' + props.userid);
            if (resp.ok) {
                let data = await resp.json();
                setMsglist(data);
            }
        }
        if (props.userid != '')
            getdata();
        return () => {

        };
    }, [props.userid])

    let send = async () => {
        if (window.user == undefined) {
            window.location.href = '/login';
            return;
        }
        if (props.userid == window.user.id) {
            alert("不能给自己留言");
            return;
        }
        setIsSend(true);
        let data = new FormData();
        data.append('userto', props.userid);
        data.append('userid', window.user.id);
        data.append('content', msg)
        let resp = await fetch('/api/index/sendMsg', {
            method: 'POST',
            body: data
        });
        setIsSend(false);
        if (resp.ok) {
            setMsg('');
            alert('留言完成');
        } else {
            alert('留言失败');
        }
    }
    return (
        <div className='board'>
            <div className='board-title'>留言板</div>
            <div className='message-list'>
                {msglist.map((item) => {
                    return <BoardItem data={item} key={item.id} userid={window.userid}/>
                })}
            </div>
            <div className='send-div'>
                <textarea className="textarea" onChange={e => { setMsg(e.target.value) }}></textarea>
                {issend ? <Spinner></Spinner> : <Button style={{ float: "right", margin: 8 }} onClick={send}>给我留言</Button>}
            </div>

        </div>
    )
}

export default Board
